<template>
  <div class="finance-report">
    <!-- 报表筛选 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="报表类型">
          <el-select v-model="filterForm.reportType" @change="loadReportData">
            <el-option label="收支报表" value="income_expense" />
            <el-option label="利润报表" value="profit" />
            <el-option label="订单报表" value="order" />
            <el-option label="客户报表" value="customer" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="YYYY-MM"
            @change="loadReportData"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleExportReport">
            <el-icon><Download /></el-icon>
            导出报表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 财务概览 -->
    <el-row :gutter="20" class="overview-row">
      <el-col :span="6">
        <el-card class="overview-card income">
          <div class="overview-content">
            <div class="overview-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="overview-info">
              <h3>¥{{ formatMoney(overview.totalIncome) }}</h3>
              <p>总收入</p>
              <span class="growth positive">+12.5%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card expense">
          <div class="overview-content">
            <div class="overview-icon">
              <el-icon><CreditCard /></el-icon>
            </div>
            <div class="overview-info">
              <h3>¥{{ formatMoney(overview.totalExpense) }}</h3>
              <p>总支出</p>
              <span class="growth negative">+5.2%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card profit">
          <div class="overview-content">
            <div class="overview-icon">
              <el-icon><Money /></el-icon>
            </div>
            <div class="overview-info">
              <h3>¥{{ formatMoney(overview.totalProfit) }}</h3>
              <p>净利润</p>
              <span class="growth positive">+8.3%</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="overview-card margin">
          <div class="overview-content">
            <div class="overview-icon">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="overview-info">
              <h3>{{ overview.profitMargin }}%</h3>
              <p>利润率</p>
              <span class="growth positive">+2.1%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 收支趋势图 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <span>收支趋势图</span>
          </template>
          <div ref="trendChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <!-- 收入结构饼图 -->
      <el-col :span="8">
        <el-card>
          <template #header>
            <span>收入结构</span>
          </template>
          <div ref="pieChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 月度对比图 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>月度收支对比</span>
          </template>
          <div ref="barChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>详细数据</span>
          </template>
          <el-table :data="reportData" border stripe>
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="income" label="收入" width="120">
              <template #default="{ row }">
                <span class="income-text">¥{{ formatMoney(row.income) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="expense" label="支出" width="120">
              <template #default="{ row }">
                <span class="expense-text">¥{{ formatMoney(row.expense) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="profit" label="利润" width="120">
              <template #default="{ row }">
                <span :class="row.profit >= 0 ? 'profit-positive' : 'profit-negative'">
                  ¥{{ formatMoney(row.profit) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="orderCount" label="订单数" width="100" />
            <el-table-column prop="customerCount" label="客户数" width="100" />
            <el-table-column prop="profitMargin" label="利润率" width="100">
              <template #default="{ row }">
                {{ row.profitMargin }}%
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { 
  TrendCharts, CreditCard, Money, DataAnalysis, Download 
} from '@element-plus/icons-vue'
import { getFinanceReport, exportFinanceReport } from '@/api/wash_service'

export default {
  name: 'FinanceReport',
  components: {
    TrendCharts, CreditCard, Money, DataAnalysis, Download
  },
  setup() {
    const trendChart = ref()
    const pieChart = ref()
    const barChart = ref()

    const filterForm = reactive({
      reportType: 'income_expense',
      dateRange: []
    })

    const overview = reactive({
      totalIncome: 0,
      totalExpense: 0,
      totalProfit: 0,
      profitMargin: 0
    })

    const reportData = ref([])
    const chartData = ref({
      trend: { dates: [], income: [], expense: [], profit: [] },
      pie: [],
      bar: { dates: [], income: [], expense: [] }
    })

    let trendChartInstance = null
    let pieChartInstance = null
    let barChartInstance = null

    const formatMoney = (amount) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount)
    }

    const initTrendChart = () => {
      if (!trendChart.value) return
      
      trendChartInstance = echarts.init(trendChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['收入', '支出', '利润']
        },
        xAxis: {
          type: 'category',
          data: chartData.value.trend.dates
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '收入',
            type: 'line',
            data: chartData.value.trend.income,
            itemStyle: { color: '#67C23A' },
            smooth: true
          },
          {
            name: '支出',
            type: 'line',
            data: chartData.value.trend.expense,
            itemStyle: { color: '#F56C6C' },
            smooth: true
          },
          {
            name: '利润',
            type: 'line',
            data: chartData.value.trend.profit,
            itemStyle: { color: '#409EFF' },
            smooth: true
          }
        ]
      }
      
      trendChartInstance.setOption(option)
    }

    const initPieChart = () => {
      if (!pieChart.value) return
      
      pieChartInstance = echarts.init(pieChart.value)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '收入结构',
            type: 'pie',
            radius: '70%',
            data: chartData.value.pie,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      
      pieChartInstance.setOption(option)
    }

    const initBarChart = () => {
      if (!barChart.value) return
      
      barChartInstance = echarts.init(barChart.value)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['收入', '支出']
        },
        xAxis: {
          type: 'category',
          data: chartData.value.bar.dates
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '收入',
            type: 'bar',
            data: chartData.value.bar.income,
            itemStyle: { color: '#67C23A' }
          },
          {
            name: '支出',
            type: 'bar',
            data: chartData.value.bar.expense,
            itemStyle: { color: '#F56C6C' }
          }
        ]
      }
      
      barChartInstance.setOption(option)
    }

    const loadReportData = async () => {
      try {
        const res = await getFinanceReport({
          reportType: filterForm.reportType,
          dateRange: filterForm.dateRange
        })
        
        if (res && (res.code === 200 || res.data)) {
          const data = res.data || res
          
          // 更新概览数据
          Object.assign(overview, {
            totalIncome: data.overview?.totalIncome || 0,
            totalExpense: data.overview?.totalExpense || 0,
            totalProfit: data.overview?.totalProfit || 0,
            profitMargin: data.overview?.profitMargin || 0
          })
          
          // 更新表格数据
          reportData.value = data.details || []
          
          // 更新图表数据
          chartData.value = {
            trend: data.trendChart || { dates: [], income: [], expense: [], profit: [] },
            pie: data.pieChart || [],
            bar: data.barChart || { dates: [], income: [], expense: [] }
          }
          
          // 重新初始化图表
          await nextTick()
          initTrendChart()
          initPieChart()
          initBarChart()
        }
      } catch (error) {
        console.error('获取财务报表失败:', error)
        ElMessage.warning('获取财务报表失败，请检查网络连接')
        
        // 重置数据
        Object.assign(overview, {
          totalIncome: 0,
          totalExpense: 0,
          totalProfit: 0,
          profitMargin: 0
        })
        reportData.value = []
        chartData.value = {
          trend: { dates: [], income: [], expense: [], profit: [] },
          pie: [],
          bar: { dates: [], income: [], expense: [] }
        }
      }
    }

    const handleExportReport = async () => {
      try {
        const res = await exportFinanceReport({
          reportType: filterForm.reportType,
          dateRange: filterForm.dateRange
        })
        
        if (res && (res.code === 200 || res.success)) {
          ElMessage.success('报表导出成功')
        }
      } catch (error) {
        console.error('导出财务报表失败:', error)
        ElMessage.error('导出失败')
      }
    }

    const resizeCharts = () => {
      if (trendChartInstance) trendChartInstance.resize()
      if (pieChartInstance) pieChartInstance.resize()
      if (barChartInstance) barChartInstance.resize()
    }

    onMounted(async () => {
      await nextTick()
      loadReportData()
      
      window.addEventListener('resize', resizeCharts)
    })

    return {
      trendChart,
      pieChart,
      barChart,
      filterForm,
      overview,
      reportData,
      formatMoney,
      loadReportData,
      handleExportReport
    }
  }
}
</script>

<style scoped>
.finance-report {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.overview-row {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.overview-card.income {
  border-left: 4px solid #67C23A;
}

.overview-card.expense {
  border-left: 4px solid #F56C6C;
}

.overview-card.profit {
  border-left: 4px solid #409EFF;
}

.overview-card.margin {
  border-left: 4px solid #E6A23C;
}

.overview-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.overview-icon {
  font-size: 40px;
  margin-right: 20px;
  color: #909399;
}

.overview-info h3 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.overview-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.growth {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.growth.positive {
  background-color: #f0f9ff;
  color: #67C23A;
}

.growth.negative {
  background-color: #fef0f0;
  color: #F56C6C;
}

.income-text {
  color: #67C23A;
  font-weight: bold;
}

.expense-text {
  color: #F56C6C;
  font-weight: bold;
}

.profit-positive {
  color: #67C23A;
  font-weight: bold;
}

.profit-negative {
  color: #F56C6C;
  font-weight: bold;
}
</style> 